﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Yaxunsoft.CasesManagement;
using FantastPlatform.Framework.IModel;
using FantastPlatform.Community.Model;
using FantastPlatform.Community.IService;
using FantastPlatform.Framework;
using FantastPlatform.Community.IMode;
using System.Web.Script.Serialization;
using NHibernate;
using FantastPlatform.Framework.Core;
using FantastPlatform.Framework.IService;
using System.IO;

namespace FantastPlatform.Community.UI.Service
{
    public partial class BusinessService : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginEmployee = Session["User"] as FantastPlatform.Framework.Model.Employee;
            int totalCount = 0;
            ConditionGroup group = new ConditionGroup();
            IBusiness business;
            group.Conditions.Add(new Condition() { Field = "Enable", Type = typeof(bool).FullName, Value1 = true });
            IBusinessService businessService = ServiceFactory.CreateService<IBusinessService>();
            IPersonService personService;
            switch (Action)
            {
                case "Add":
                    string[] arrStreet = null;
                    string[] arrResponsibilityArea = null;
                    string[] arrStation = null;
                    int station = 0;
                    if (!string.IsNullOrEmpty(Request["PoliceStation"]))
                    {
                        arrStation = Request["PoliceStation"].Split(',');
                        station = Int32.Parse(arrStation[0]);
                    }
                    int street = 0;
                    if (!string.IsNullOrEmpty(Request["Street"]))
                    {
                        arrStreet = Request["Street"].Split(',');
                        street = Int32.Parse(arrStreet[0]);
                    }
                    int responsibilityArea = 0;
                    if (!string.IsNullOrEmpty(Request["ResponsibilityArea"]))
                    {
                        arrResponsibilityArea = Request["ResponsibilityArea"].Split(',');
                        responsibilityArea = Int32.Parse(arrResponsibilityArea[0]);
                    }
                    business = JsonToEntity<Business>(Data);
                    business.Persons = new List<FantastPlatform.Community.IMode.IPerson>();
                    GetPurpose(business);
                    GetPlaceType(business);
                    if (arrResponsibilityArea != null)
                    {
                        business.Code = arrResponsibilityArea[1] + arrStreet[1] + AddressToCode(business.Address) + "000000";
                    }
                    business.Station = new FantastPlatform.Framework.Model.Organization() { Id = station };
                    business.ResponsibilityArea = new FantastPlatform.Framework.Model.Organization() { Id = responsibilityArea };
                    business.Street = new FantastPlatform.Framework.Model.Street() { Id = street };
                    business.PoliceMan = LoginEmployee;
                    if (business.Id == 0)
                    {
                        business.Enable = true;
                        businessService.Create(business);
                    }
                    else
                    {
                        IBusiness oldbusiness = businessService.Get(business.Id);
                        business.Persons = oldbusiness.Persons;
                        business.CreateDate = oldbusiness.CreateDate;
                        businessService.Update(business);
                    }
                    ReturnSuccessMessage("保存商业店铺成功！");

                    break;
                case "Search":
                    IOrganization org;
                    if (LoginEmployee != null)
                    {
                        org = (from o in LoginEmployee.EmployeePosts
                               where o.Enable = true
                               select o.Post.Organization).FirstOrDefault();
                        if (LoginEmployee.User != null)
                        {
                            IList<IRole> roleList = LoginEmployee.User.Roles;
                            List<string> roles = new List<string>();
                            foreach (IRole role in roleList)
                            {
                                roles.Add(role.Name);
                            }
                            if (roles.Contains("社区一级管理员") || roles.Contains("管理员"))
                            {
                            }
                            else if (roles.Contains("社区二级管理员"))
                            {
                                group.Conditions.Add(new Condition() { Field = "PoliceMan.EmployeePosts.Post.Organization.Id", Relation = Relations.And, Type = typeof(Int32).FullName, Value1 = org.Id });
                            }
                            else
                            {
                                group.Conditions.Add(new Condition() { Field = "PoliceMan.Id", Relation = Relations.And, Type = typeof(Int32).FullName, Value1 = LoginEmployee.Id });
                            }
                        }
                    }
                    IList<IBusiness> list = businessService.Search(group, null, PageSize, SelfPage, out totalCount);
                    object[] businessObjList = (from o in list
                                                select new
                                                {
                                                    Name = o.Name,
                                                    Range = o.Range,
                                                    Address = o.Station.Name + o.ResponsibilityArea.Name + o.Street.Name + o.Address,
                                                    Code = o.Code,
                                                    Description = o.Description,
                                                    Id = o.Id,
                                                    Purpose = string.Join(",", (from p in o.Purposes where p.Enable == true select p.Name).ToArray()),
                                                    PlaceType = string.Join(",", (from p in o.PlaceTypes where p.Enable == true select p.Name).ToArray()),
                                                    Owner = (from p in o.Persons where p.Enable == true && p.PersonType.Name == "房主" select p.Name).FirstOrDefault(),
                                                    Leader = (from p in o.Persons where p.Enable == true && p.PersonType.Name == "承租人" select p.Name).FirstOrDefault(),
                                                    Unit = (from p in o.PoliceMan.EmployeePosts
                                                            where p.Enable = true
                                                            select p.Post.Organization.Name),
                                                    PoliceMan = o.PoliceMan.Code,
                                                    CreateDate = o.CreateDate,
                                                    Enable = o.Enable
                                                }).ToArray();
                    ReturnList(totalCount, businessObjList);
                    break;
                case "SearchByCondition":
                    string Searchjson = RepairString(Data);
                    business = JsonToEntity<Business>(Searchjson);
                    IList<IBusiness> housedistrictList1 = businessService.SearchByCondition(business.Name, business.Address, LoginEmployee.Id);
                    businessObjList = (from o in housedistrictList1
                                       select new
                                       {
                                           Name = o.Name,
                                           Address = o.Station.Name + o.ResponsibilityArea.Name + o.Street.Name + o.Address,
                                           Description = o.Description,
                                           Id = o.Id,
                                           Purpose = string.Join(",", (from p in o.Purposes where p.Enable == true select p.Name).ToArray()),
                                           PlaceType = string.Join(",", (from p in o.PlaceTypes where p.Enable == true select p.Name).ToArray()),
                                           Owner = (from p in o.Persons where p.Enable == true && p.PersonType != null && p.PersonType.Name == "房主" select p.Name).FirstOrDefault(),
                                           Leader = (from p in o.Persons where p.Enable == true && p.PersonType != null && p.PersonType.Name == "承租人" select p.Name).FirstOrDefault(),
                                           Unit = (from p in o.PoliceMan.EmployeePosts
                                                   where p.Enable = true
                                                   select p.Post.Organization.Name),
                                           PoliceMan = o.PoliceMan.Code,
                                           CreateDate = o.CreateDate,
                                           Enable = o.Enable
                                       }
                                                ).ToArray();
                    ReturnList(businessObjList.Length, businessObjList);
                    break;
                case "GetPlaceType":
                    IPlaceTypeService typeService = ServiceFactory.CreateService<IPlaceTypeService>();
                    IList<IPlaceType> placeTypeList = typeService.LoadList(null, Int32.MaxValue, 1, out totalCount);
                    object[] objList = (from o in placeTypeList
                                        select new
                                        {
                                            Id = o.Id,
                                            Name = o.Name,
                                            Code = o.Code,
                                            CreateDate = o.CreateDate,
                                            Enable = o.Enable
                                        }
                                            ).ToArray();
                    ReturnList(totalCount, objList);
                    break;
                case "GetPurPose":
                    IPurposeService purposeService = ServiceFactory.CreateService<IPurposeService>();
                    IList<IPurpose> purposeList = purposeService.LoadList(null, Int32.MaxValue, 1, out totalCount);
                    objList = (from o in purposeList
                               select new
                               {
                                   Id = o.Id,
                                   Name = o.Name,
                                   Code = o.Code,
                                   CreateDate = o.CreateDate,
                                   Enable = o.Enable
                               }
                                           ).ToArray();
                    ReturnList(totalCount, objList);
                    break;
                case "Get":
                    business = businessService.Get(Id);

                    object obj = new
                    {
                        Id = business.Id,
                        Name = business.Name,
                        CreateDate = business.CreateDate,
                        Enbale = business.Enable,
                        Address = business.Address,
                        Range = business.Range,
                        Description = business.Description,
                        CreatePoliceManNumber = business.PoliceMan.Code,
                        OrganizationName = business.Station.Id + "," + business.Station.Code + "|" + business.Station.Name,
                        ResponsibilityAreaName = business.ResponsibilityArea.Id + "," + business.ResponsibilityArea.Code + "|" + business.ResponsibilityArea.Name,
                        StreetName = business.Street.Id + "," + business.Street.Code + "|" + business.Street.Name
                    };
                    ReturnObj(obj);
                    break;
                case "GetPlaceTypeByPersonId":

                    business = businessService.Get(Id);
                    string placeType = string.Join(",", (from pt in business.PlaceTypes
                                                         where pt.Enable = true
                                                         select pt.Id.ToString()).ToArray<string>());
                    ReturnSuccessMessage(placeType);
                    break;

                case "GetPurposeByBusinessId":

                    business = businessService.Get(Id);
                    string purpose = string.Join(",", (from p in business.Purposes
                                                       where p.Enable = true
                                                       select p.Id.ToString()).ToArray<string>());
                    ReturnSuccessMessage(purpose);
                    break;
                case "DeletePerson":
                    personService = ServiceFactory.CreateService<IPersonService>();
                    List<int> ids = new List<int>();
                    string[] idArray = Data.Split(',');
                    foreach (string id in idArray)
                    {
                        ids.Add(int.Parse(id));
                    }
                    personService.Delete(ids);
                    ReturnSuccessMessage("移除记录成功");

                    break;
                case "Delete":
                    ids = new List<int>();
                    idArray = Data.Split(',');
                    foreach (string id in idArray)
                    {
                        ids.Add(int.Parse(id));
                    }
                    businessService.Delete(ids);
                    ReturnSuccessMessage("移除记录成功");
                    break;
                case "GetStreets":
                    string code = "";
                    if (!string.IsNullOrEmpty(Request["code"]))
                    {
                        code = Request["code"];
                    }
                    string parentCode = "";
                    if (!string.IsNullOrEmpty(Request["parentCode"]))
                    {
                        parentCode = Request["parentCode"];
                    }
                    totalCount = 0;

                    IList<IStreet> areaStreetlist = new List<IStreet>();


                    IStreetService streetService = ServiceFactory.CreateService<IStreetService>();
                    IList<IStreet> list3 = streetService.SearchStreet(code, PageSize, SelfPage, out totalCount);

                    object[] objArr = (from o in list3
                                       select new
                                       {
                                           Id = o.Id,
                                           Code = o.Code,
                                           Name = o.Name
                                       }
                                    ).ToArray();
                    ReturnList(totalCount, objArr);

                    break;
                case "AddBusinessImage":

                    string data = Data;
                    if (String.IsNullOrEmpty(data))
                    {
                        throw new Exception("传入的数据为空");
                    }
                    BusinessImageView imageView = JsonToEntity<BusinessImageView>(RepairString(data));
                    totalCount = 0;

                    IBusinessImageService businessImageService = ServiceFactory.CreateService<IBusinessImageService>();
                    IBusinessImage businessImage = businessImageService.Get(imageView.Id);
                    if (businessImage == null)
                    {
                        // caseCallBack2.CaseId = Id;
                        businessImage = new BusinessImage();
                        businessImage.Name = imageView.Name;
                        businessImage.Description = imageView.Description;
                        businessImage.Business = new Business() { Id = imageView.HouseId };
                        businessImage.ImagePath = imageView.ImageUrl;
                        businessImageService.Create(businessImage);
                        ReturnSuccessMessage("图片信息添加成功");
                    }
                    else
                    {
                        //增加判断，在更新时是否重新上传图片，重新上传图片则进行旧图片的删除。
                        //  ICaseCallBack caseCallBackOld = service.Get(caseCallBack2.Id);
                        if (!imageView.ImageUrl.Equals(businessImage.ImagePath))
                        {
                            //以下删除旧图片功能于2009/09/07增加 By杨雄
                            //找到未更新前的警种图片，并删除
                            string imgname = businessImage.ImagePath;
                            string imgurl = Server.MapPath("../upload/") + imgname;
                            if (File.Exists(imgurl))
                            {
                                File.Delete(imgurl);
                            }
                        }
                        businessImage.Name = imageView.Name;
                        businessImage.Description = imageView.Description;
                        businessImage.ImagePath = imageView.ImageUrl;
                        businessImageService.Update(businessImage);
                        ReturnSuccessMessage("图片信息更新成功");
                       
                    }
                    break;
                case "GetBusinessImage":
                    businessImageService = ServiceFactory.CreateService<IBusinessImageService>();
                    businessImage = businessImageService.Get(Id);
                    if (businessImage == null)
                    {
                        businessImage = new BusinessImage();
                    }
                    object objImage = new
                    {
                        Id = businessImage.Id,
                        Name = businessImage.Name,
                        Description = businessImage.Description,
                        ImageUrl = businessImage.ImagePath,
                        HouseId = businessImage.Business.Id
                    };
                    ReturnObj(objImage);
                    break;
                case "SearchImage":
                    businessImageService = ServiceFactory.CreateService<IBusinessImageService>();
                    group.Conditions.Add(new Condition() { Type = typeof(int).FullName, Field = "Business.Id", Value1 = Id });
                   
                    IList<IBusinessImage> imageList = businessImageService.Search(group, null, PageSize, SelfPage, out totalCount);
                    object[] imageObj = (from l in imageList
                                         select new
                                         {
                                             Id = l.Id,
                                             Name = l.Name,
                                             Description = l.Description,
                                             ImagePath = l.ImagePath
                                         }).ToArray();
                    ReturnList(totalCount, imageObj);
                    break;
                case "DeleteImage":
                    ids = new List<int>();
                    idArray = Data.Split(',');
                    foreach (string id in idArray)
                    {
                        ids.Add(int.Parse(id));
                    }
                    businessImageService = ServiceFactory.CreateService<IBusinessImageService>();
                    businessImageService.Delete(ids);
                    ReturnSuccessMessage("移除记录成功");
                    break;
            }
        }

        private void GetPurpose(IBusiness business)
        {
            string[] ptIds;

            if (!string.IsNullOrEmpty(Request["PurPose"]))
            {
                ptIds = Request["Purpose"].Split(',');

                if (ptIds.Length > 0)
                {
                    business.Purposes = new List<IPurpose>();
                    foreach (string id in ptIds)
                    {
                        business.Purposes.Add(new Purpose() { Id = Int32.Parse(id) });

                    }
                }
            }

        }

        private void GetPlaceType(IBusiness business)
        {
            string[] Ids;
            if (!string.IsNullOrEmpty(Request["PlaceType"]))
            {
                Ids = Request["PlaceType"].Split(',');
                if (Ids.Length > 0)
                {
                    business.PlaceTypes = new List<IPlaceType>();
                    foreach (string id in Ids)
                    {
                        business.PlaceTypes.Add(new PlaceType() { Id = Int32.Parse(id) });

                    }
                }
            }
        }

        private IMode.IPerson GetOwner(BusinessPerson bp)
        {
            IMode.IPerson person = new Person();
            person.Id = bp.Id;
            person.IdCard = bp.IdCard;
            person.Name = bp.Name;
            person.Nation = bp.Nation;
            person.NativePlace = bp.NativePlace;
            person.Phone = bp.Phone;
            person.QQ = bp.QQ;
            person.RegisterAddress = bp.RegisterAddress;
            person.Sex = bp.Sex;
            person.Address = bp.Address;
            person.Description = bp.Address;
            return person;
        }
        private string AddressToCode(string address)
        {
            string code = string.Empty;
            Random rd = new Random();
            string rdStr = rd.Next(9999).ToString("D6");
            try
            {
                string[] nums = address.Split('组');
                if (nums.Length > 1)
                {
                    int num1 = Convert.ToInt32(nums[0]);
                    int num2 = Convert.ToInt32(nums[1].Split('号')[0]);
                    rdStr = num1.ToString("D2") + num2.ToString("D4");
                }
                else
                {
                    nums = address.Split('号');
                    int num1 = Convert.ToInt32(nums[0]);
                    int num2 = 0;
                    if (!string.IsNullOrEmpty(nums[1]))
                        num2 = Convert.ToInt32(nums[1].Split('附')[1]);
                    rdStr = num1.ToString("D4") + num2.ToString("D2");
                }
            }
            catch (Exception ex)
            {
            }
            return rdStr;
        }
        private void GetBusinessPersons(IBusiness business)
        {
            string Data1 = "";
            if (!string.IsNullOrEmpty(Request["data1"]))
            {
                Data1 = Request["data1"];
            }
            business.Persons = JsonToEntity<List<FantastPlatform.Community.IMode.IPerson>>(RepairString(Data1));
        }
        public class BusinessPersons
        {
            public List<BusinessPerson> Persons { get; set; }
        }

        public class BusinessPerson
        {
            public int Id { get; set; }
            public string QQ { get; set; }
            public string Phone { get; set; }
            public string Address { get; set; }
            public string Nation { get; set; }
            public string NativePlace { get; set; }
            public string RegisterAddress { get; set; }
            public string PersonType { get; set; }
            public string Sex { get; set; }
            public string Name { get; set; }
            public string IdCard { get; set; }
            public string Description { get; set; }
            public DateTime? CreateDate { get; set; }
            public bool? Enable { get; set; }
            public List<Car> Cars { get; set; }
        }
        public class BusinessImageView
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Description { get; set; }
            public int HouseId { get; set; }
            public string ImageUrl { get; set; }
        }


    }
}